﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.Geodatabase;
using System.Diagnostics;

namespace CanSWAT.ArcSWAT.Soil
{
    /// <summary>
    /// A polygon in the soil map
    /// </summary>
    class SoilPolygon
    {
        public SoilPolygon(IFeature fea)
        {
            _id = ArcGISRow.ReadString(fea as IRow, "POLY_ID");
        }

        private string _id = "";
        private List<SoilComponent> _cmps = new List<SoilComponent>();

        public string ID { get { return _id; } }
        public List<SoilComponent> Components
        {
            get { return _cmps; }
            set { _cmps = value; }
        }
        public override string ToString()
        {
            string s = _id;
            foreach (SoilComponent cmp in _cmps)
                s += "_" + cmp.Percent.ToString();

            return s;
        }

        SoilComponent _mergedCmp = null;

        /// <summary>
        /// The single component is the polygon. 
        /// </summary>
        /// <remarks>It could be one original component or a new coponent merged from several components.</remarks>
        public SoilComponent MergedComponent
        {
            get
            {
                if (_mergedCmp == null)
                {
                    if (_cmps.Count == 0) return null;
                    if (_cmps.Count == 1) _mergedCmp = _cmps[0];

                    foreach (SoilComponent cmp in _cmps)
                    {
                        if (_mergedCmp == null) _mergedCmp = cmp;
                        else _mergedCmp = _mergedCmp.Merge(cmp);
                    }

                    //check if the polygon is completed
                    if (_mergedCmp.Percent < 1)
                        Debug.WriteLine("The polygon " + _id + " is not completed.");
                }
                return _mergedCmp;
            }
        }
    }
}
